package datasrv

import (
	"chatgpt/helper"
	"chatgpt/helper/code"
	"chatgpt/logq"
	"chatgpt/plugin/httpsrv"
	"chatgpt/plugin/rpcx"
	"fmt"
)

var (
	SystemSrv SystemApi
)

func Init() {
	rpcx.DataSrv = rpcx.NewRpcxClient(RegisterSrv())
	rpcx.RegisterDataSrv("ServerDescSync")
	rpcx.RegisterDataSrv("SqlExec")
	rpcx.RegisterDataSrv("UserApi")
	rpcx.RegisterDataSrv("DeviceApi")
	rpcx.RegisterDataSrv("SpaceApi")
	rpcx.RegisterDataSrv("AccountApi")
	rpcx.RegisterDataSrv("BannerApi")
	rpcx.RegisterDataSrv("OutApi")
	rpcx.RegisterDataSrv("CounterApi")
	rpcx.RegisterDataSrv("SystemApi")
}

type ResponseAddrs struct {
	MsgCode int
	Data    []string
}

type ResponseData struct {
	MsgCode int
	Data    any
}

type ResponseDesc struct {
	MsgCode code.CODENO
	Data    interface{}
	Desc    string
}

func RegisterSrv() []string {
	addr_url := "/system/addrs?"
	res := ResponseAddrs{}
	param := fmt.Sprintf("AuthToken=%v", Login2Datasrv())
	err := httpsrv.Get(httpsrv.DataSrvRoute(addr_url)+param, &res)

	if err != nil {
		logq.Error("Init.RegisterSrv err: ", err)
		return []string{}
	}
	data := res.Data
	return data
}

func Login2Datasrv() string {
	login_url := "/system/login?"
	res := ResponseDesc{}
	cnf := helper.Config().Sub("DataSrv")
	param := fmt.Sprintf("Account=%s&Passwd=%s", cnf.GetString("account"), cnf.GetString("password"))
	err := httpsrv.Get(httpsrv.DataSrvRoute(login_url)+param, &res)
	if err != nil {
		logq.Error("Init.Login2Datasrv err: ", err)
		return ""
	}

	data, ok := res.Data.(map[string]any)
	if !ok {
		return ""
	}

	if val, ok := data["AuthToken"]; ok {
		return val.(string)
	}
	return ""
}
